#pragma once

#include <iostream>
#include <cstdlib>
#include <string>
#include <sys/epoll.h>
#include "Err.hpp"
#include "log.hpp"

static const int defaultepfd = -1;
static const int gsize = 128;

class Epoller
{
public:
    Epoller() : _epfd(defaultepfd)
    {
    }
    ~Epoller()
    {
    }

    void Create()
    {
        _epfd = epoll_create(gsize);
        if (_epfd < 0)
        {
            logmessage(FATAL, "epoll create error, %s", strerror(errno));
            exit(EPCREAT_ERR);
        }
    }

    bool AddEvent(int fd, uint16_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = fd;

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
        if (n < 0)
        {
            logmessage(FATAL, "epol_ctl error, %s", strerror(errno));
            return false;
        }
        return true;
    }

    bool Wait(struct epoll_event *revs, int num, int timeout)
    {
        return epoll_wait(_epfd, revs, num, timeout);
    }

    bool DelEvent(int fd)
    {
        return epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr) == 0;
    }

    int Fd()
    {
        return _epfd;
    }

    void Close()
    {
        if (_epfd != defaultepfd)
            close(_epfd);
    }

private:
    int _epfd;
};